package com.sun.showcase.controller.app;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.sun.showcase.conf.wx.miniapp.WxMaConfiguration;
import com.sun.showcase.pojo.Result;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import me.chanjar.weixin.common.error.WxErrorException;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/app/wx/{appid}")
public class WxMaUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 登陆接口
     */
	@ResponseBody
	@RequestMapping(value="/openid")
    public Result login(@PathVariable String appid, String code) {
		Result result = new Result();
        if (StringUtils.isBlank(code)) {
        	result.setSuccess(false);
        	result.setMsg("无效code");
            return result;
        }
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            result.setSuccess(true);
            result.setData(session.getOpenid());
            return result;
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            result.setSuccess(false);
        	result.setMsg("获取openid失败");
            return result;
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
	@ResponseBody
	@RequestMapping(value="/info")
    public Result info(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
    	Result result = new Result();
    	result.setSuccess(true);
    	final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
        	result.setSuccess(false);
        	result.setMsg("user check failed");
            return result;
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        result.setData(userInfo);
        return result;
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public Result phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
    	Result result = new Result();
    	result.setSuccess(true);
    	final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
        	result.setSuccess(false);
        	result.setMsg("user check failed");
            return result;
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        result.setData(phoneNoInfo);
        return result;
    }

}
